
//axios全局设置，请求拦截器
axios.interceptors.request.use(
    (config)=>{
        config.headers['Authorization'] = 'Bearer' + ' ' + localStorage.getItem('token');
        return config;
    },
    (error)=>{
        return Promise.reject(error);
    }
)

//axios全局设置，响应拦截器
axios.interceptors.response.use(
    (res)=>{
        return res;
    },
    (error)=>{
        if(error.response.status == 401){
            localStorage.removeItem('token');
            location.href = './登录.html';
        }else if(error.response.status == 404){
            alert('访问路径错误！');
        }else if(error.response.status == 500){
            alert('服务器内部错误！');
        }
        return Promise.reject(error);
    }
)

//渲染列表
function render(data) {
    var str = ''

    str = data.map((item, index) => {
        return `<tr>
        <td>${item.email}</td>
        <td>${item.name}</td>
        <td>${item.phone}</td>
        <td>${item.ingroup}</td>
        <td>${item.isadmin ? "是" : "否"}</td>
        <td class="${item.status ? '' : 'bac'}">${item.status ? "正常" : "异常"}</td>
        <td><span class="iconfont icon-bianji"></span>&emsp;<span class="iconfont icon-shanchu"></span></td>
    </tr>`
    }).join('')

    if (str == '') {
        str = '<div style="text-align:center;color:red">未查询到数据!</div>'
    }
    document.querySelector('table tbody').innerHTML = str;
}



//分页请求
axios.get('/user/list', {params: {page: 1, count: 5}}).then((res) => {
    render(res.data.list);
})
//点击下一页
var num = 1;
document.querySelector('.change .next').onclick = () => {
    num++;
    if (num >= 2) {
        num = 2;
    }
    axios.get('/user/list', {params:{page: num, count: 5}}).then((res) => {
        render(res.data.list);
    })
}
//点击上一页
document.querySelector('.change .prev').onclick = () => {
    num--;
    if (num <= 1) {
        num = 1;
    }
    axios.get('/user/list', {params: {page: num, count: 5}}).then((res) => {
        render(res.data.list);
    })
}

//搜索
var findBtn = document.querySelector('.find button');
var inputEle = document.querySelector('.find input');
findBtn.onclick = () => {
    axios.get('/user/search', { params: { searchkey: inputEle.value } }).then((res) => {
        render(res.data.list)
    })
}

//删除
document.querySelector('tbody').onclick = (e)=>{
    if(e.target.classList.contains('icon-shanchu')){
        e.target.parentNode.parentNode.remove();
    }
}